﻿using mozhi.smarterp.Finance.Accounts.Repository;
using mozhi.smarterp.Finance.Basedatas;
using mozhi.smarterp.Finance.Basedatas.Repository;
using mozhi.smarterp.Finance.Enums;
using mozhi.smarterp.Finance.Querys;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Domain.Services;
using Volo.Abp.Guids;

namespace mozhi.smarterp.Finance.Accounts
{
    public class AccountDimensionManager : DomainServiceBase
    {
        private IAccountDimensionRepository _dimensionRepository;
        private ITagRepository _tagRepository;
        private IGuidGenerator _guidGenerator;
        public AccountDimensionManager(IAccountDimensionRepository dimensionRepository, IGuidGenerator guidGenerator,
            ITagRepository tagRepository,
            IDataAssociationRepository dataAssociationRepository)
            : base(dataAssociationRepository)
        {
            this._dimensionRepository = dimensionRepository;
            this._guidGenerator = guidGenerator;
            this._tagRepository = tagRepository;
        }

        public async Task<AccountDimension> Instance(string code, string name, DataSourceType dataSourceType)
        {
            await ValidateDuplicate(code, name);

            var dimension = new AccountDimension(_guidGenerator.Create(), code, name, dataSourceType, true);

            return dimension;
        }

        public async Task ValidateDuplicate(string code, string name, Guid? currentId = null)
        {
            var codeExistCount = await _dimensionRepository.GetCountAsync(new PageQuery() { Keyword = code, ExclusionId = currentId });

            if (codeExistCount > 0)
                throw new UserFriendlyException("核算维度编码重复", "100000");

            var nameExistCount = await _dimensionRepository.GetCountAsync(new PageQuery() { Keyword = name, ExclusionId = currentId });

            if (nameExistCount > 0)
                throw new UserFriendlyException("核算维度名称重复", "100000");
        }

        public async Task ChangeType(AccountDimension dimension, DataSourceType type, Guid? tagId)
        {
            var dataAssociations = await GetDataAssociationDetail(dimension.Id);

            if (dataAssociations.Count > 0)
                throw new UserFriendlyException($"存在数据引用:{string.Join(";", dataAssociations)},不能更改核算维度数据类型", "100000");

            if (type == DataSourceType.Tag && !tagId.HasValue)
            {
                var tag = await _tagRepository.FindAsync(tagId.Value);

                if (tag == null)
                    throw new UserFriendlyException($"标签不存在", "100000");

                if (!tag.Activated)
                    throw new UserFriendlyException($"标签已禁用", "100000");
            }

            dimension.ChangeType(type, tagId);
        }
    }
}
